/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.store.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.msg.service.MsgService;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.store.service.StoreService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 厂家店铺Controller
 * @author lixinapp
 * @version 2019-10-14
 */
@Controller
@RequestMapping(value = "${adminPath}/store/store")
public class StoreController extends BaseController {

	@Autowired
	private StoreService storeService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public Store get(@RequestParam(required=false) String id) {
		Store entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = storeService.get(id);
		}
		if (entity == null){
			entity = new Store();
		}
		return entity;
	}
	
	/**
	 * 厂家店铺列表页面
	 */
	@RequiresPermissions("store:store:list")
	@RequestMapping(value = {"list", ""})
	public String list(Store store, Model model) {
		model.addAttribute("store", store);
		return "modules/store/storeList";
	}
	
		/**
	 * 厂家店铺列表数据
	 */
	@ResponseBody
	@RequiresPermissions("store:store:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Store store, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			store.setUser(user);
		}
		Page<Store> page = storeService.findPage(new Page<Store>(request, response), store);
		//增加供应商数量
		Map<String, Object> json = getBootstrapData(page);
		int total;
		int count= Integer.parseInt(String.valueOf(json.get("total")));
		total = count+ 7000;
		json.put("total",total);
		return json;
	}

	/**
	 * 查看，增加，编辑厂家店铺表单页面
	 */
	@RequiresPermissions(value={"store:store:view","store:store:add","store:store:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Store store, Model model) {
		model.addAttribute("store", store);
		return "modules/store/storeForm";
	}

	/**
	 * 保存厂家店铺
	 */
	@ResponseBody
	@RequiresPermissions(value={"store:store:add","store:store:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Store store, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(store);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		if (StringUtils.isNotBlank(store.getDistant()) && store.getArea() != null && StringUtils.isNotBlank(store.getArea().getName())) {
			store.setDistant(store.getArea().getName());
		} else {
			store.setDistant("");
		}
		if (StringUtils.isNotBlank(store.getNodelarea()) && store.getNodelarea() != null && StringUtils.isNotBlank(store.getAreatwo().getName())) {
			store.setNodelarea(store.getAreatwo().getName());
		} else {
			store.setNodelarea("");
		}
		//新增或编辑表单保存
		storeService.save(store);//保存
		j.setSuccess(true);
		j.setMsg("保存厂家店铺成功");
		return j;
	}
	
	/**
	 * 删除厂家店铺
	 */
	@ResponseBody
	@RequiresPermissions("store:store:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Store store) {
		AjaxJson j = new AjaxJson();
		storeService.delete(store);
		j.setMsg("删除厂家店铺成功");
		return j;
	}
	
	/**
	 * 审核厂家店铺
	 */
	@ResponseBody
	@RequiresPermissions("store:store:audit")
	@RequestMapping(value = "audit")
	public AjaxJson audit(Store store, String type, String reason) {
		AjaxJson j = new AjaxJson();
		if (!"1".equals(store.getAuditState()) && !"0".equals(store.getAuditState())) {
			j.setSuccess(false);
			j.setMsg("店铺状态异常");
			return j;
		}
		store.setAuditState(type);
		store.setAuditDate(new Date());
		storeService.audit(store);
		// 拒绝后发消息
		if ("3".equals(type) && StringUtils.isNotBlank(reason)) {
			msgService.insert(store.getMember(), "系统消息", "您的厂家入驻申请被拒绝，原因：" + reason);
		}
		
		j.setMsg("审核厂家店铺成功");
		return j;
	}
	
	/**
	 * 审核厂家店铺
	 */
	@ResponseBody
	@RequiresPermissions("store:store:audit")
	@RequestMapping(value = "updateState")
	public AjaxJson updateState(Store store, String type) {
		AjaxJson j = new AjaxJson();
		if (StringUtils.isNotBlank(store.getId())) {
			store.setState(type);
			storeService.save(store);
			if ("1".equals(type)) {
				// 冻结登录账号
				User user = store.getUser();
				if (user != null) {
					user = systemService.getUser(user.getId());
					if (user != null) {
						storeService.executeUpdateSql("UPDATE sys_user SET login_flag = '0' WHERE id = '"+user.getId()+"'");
						UserUtils.clearCache(user);
					}
				}
				// 下架所有商品
				storeService.executeUpdateSql("UPDATE t_product SET state = '1' WHERE store_id = '"+store.getId()+"'");
			}
		} else if ("0".equals(type)) {
			// 解冻登录账号
			User user = store.getUser();
			if (user != null) {
				user = systemService.getUser(user.getId());
				if (user != null) {
					storeService.executeUpdateSql("UPDATE sys_user SET login_flag = '1' WHERE id = '"+user.getId()+"'");
					UserUtils.clearCache(user);
				}
			}
		}
		j.setMsg("操作成功");
		return j;
	}
	
	/**
	 * 批量删除厂家店铺
	 */
	@ResponseBody
	@RequiresPermissions("store:store:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			storeService.delete(storeService.get(id));
		}
		j.setMsg("删除厂家店铺成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("store:store:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Store store, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "厂家店铺"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Store> page = storeService.findPage(new Page<Store>(request, response, -1), store);
    		new ExportExcel("厂家店铺", Store.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出厂家店铺记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("store:store:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Store> list = ei.getDataList(Store.class);
			for (Store store : list){
				try{
					storeService.save(store);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条厂家店铺记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条厂家店铺记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入厂家店铺失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入厂家店铺数据模板
	 */
	@ResponseBody
	@RequiresPermissions("store:store:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "厂家店铺数据导入模板.xlsx";
    		List<Store> list = Lists.newArrayList(); 
    		new ExportExcel("厂家店铺数据", Store.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

}